﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TrendingReader.Classes
{
    public class SettingFunctions
    {
        public static async Task SetValue(TrendingReaderEntities entities, string key, string value)
        {
            if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(value))
                return;

            if (entities == null)
                entities = new TrendingReaderEntities();

            var setting = entities.Settings.FirstOrDefault(s => s.Key.Trim() == key.Trim());

            if (setting != null)
            {
                setting.Value = value.Trim();
            }
            else
            {
                setting = new Settings {
                    Key = key.Trim(),
                    Value = value.Trim()
                };
            }

            await entities.SaveChangesAsync();
        }

        public static string GetValue(TrendingReaderEntities entities, string key)
        {
            var strRet = string.Empty;
            if (string.IsNullOrEmpty(key))
                return strRet;

            if (entities == null)
                entities = new TrendingReaderEntities();

            var setting = entities.Settings.FirstOrDefault(s => s.Key.Trim() == key.Trim());

            if (setting != null)
            {
                strRet = setting.Value.Trim();
            }

            return strRet;
        }
    }
}
